package cn.hhit.system.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.alibaba.fastjson.JSON;

import cn.dms.system.model.Department;
import cn.dms.system.service.DepartmentService;
import cn.hhit.common.action.CommonAction;
import cn.hhit.common.pagination.Page;
import cn.hhit.common.pagination.PageContext;
import cn.hhit.common.util.ExcelHelper;
import cn.hhit.common.util.HssfExcelHelper;
import cn.hhit.common.util.ListUtil;
import cn.hhit.common.util.StringUtil;
import cn.hhit.system.model.Menu;
import cn.hhit.system.model.MenuView;
import cn.hhit.system.model.PermissionModel;
import cn.hhit.system.model.RoleModel;
import cn.hhit.system.model.RoleUserViewModel;
import cn.hhit.system.model.TreeModel;
import cn.hhit.system.model.UserModel;
import cn.hhit.system.model.UserRole;
import cn.hhit.system.service.MenuService;
import cn.hhit.system.service.MenuViewService;
import cn.hhit.system.service.RoleService;
import cn.hhit.system.service.RoleUserViewService;
import cn.hhit.system.service.UserRoleService;
import cn.hhit.system.service.UserService;

@SuppressWarnings("rawtypes")
public class MenuAction extends CommonAction {
	private static final long serialVersionUID = 1L;

	@Autowired
	@Qualifier("MenuService")
	private MenuService menuService;
	@Autowired
	@Qualifier("MenuViewService")
	private MenuViewService menuViewService;

	@Autowired
	@Qualifier("UserService")
	private UserService userService;

	@Autowired
	@Qualifier("RoleService")
	private RoleService roleService;

	@Autowired
	@Qualifier("UserRoleService")
	private UserRoleService userRoleService;

	@Autowired
	@Qualifier("RoleUserViewService")
	private RoleUserViewService roleUserViewService;

	@Autowired
	@Qualifier("DepartmentService")
	private DepartmentService departmentService;

	private String action;
	private String roleids;
	private String rolename;
	private int id;
	private Integer roleid;
	private int userid;
	private UserModel user;
	private RoleModel role;
	public String jsonToSave;
	private Integer[] roleidArray;
	private int menuid;
	private String password;
	private String fileFileName; // 文件名称
	private String username;
	private String unum;
	private String deptname;

	public String showUsers() {
		return "users";
	}

	public String showRoles() {
		return "roles";
	}

	public String roleUsers() {
		return "roleusers";
	}

	public String showDepartments() {
		return "departments";
	}

	public String importUser() {
		return "importuser";
	}

	public String permsDistuibute() {
		return "perms";
	}

	public void findDepartment() {
		Department department = departmentService.get(id);
		writeObjectToClient(response, department, true);

	}

	public void editDepartment() {
		departmentService.saveOrUpdate(department);
		writeResultToClient(response, true);
	}

	public void departmentList() {
		List<Department> departments = departmentService.listByParams(" order by dindex");
		writeListToClient(response, departments, true);
	}

	public void uploadUserFile() throws Exception {
		if (file == null) {
			writeStringToClient(response, "{success:false,message:'服务端未收到文件'}", false);
			return;
		}

		String[] fieldNames = new String[] { "username", "name", "department", "major", "unum", "sex" };
		ExcelHelper eh = HssfExcelHelper.getInstance(file);
		List<UserModel> userlist = eh.readExcel(UserModel.class, fieldNames, true);
		int uindex = 1;
		for (UserModel user : userlist) {
			user.setPassword("12345678");
			user.setEditable("true");
			user.setRegisterDate(new Date());
			user.setUindex(uindex++);
			userService.saveOrUpdate(user);
			UserRole ur = new UserRole();
			ur.setUserid(user.getId());
			ur.setRoleid(100);
			userRoleService.save(ur);
		}
		writeStringToClient(response, "{success:true,message:'文件上传并导入成功',fileName:'" + fileFileName + "'}", true);
	}

	public void changePassword() {
		Integer userid = Integer.valueOf(session.get("uid").toString());
		userService.update(" set password=? where id=?", password, userid);
		writeResultToClient(response, true);
	}

	public void logout() {
		session.clear();
		writeResultToClient(response, true);
	}

	public void getRights() {
		String edit = "false";
		String department = "false";
		if (!"".equals(StringUtil.parseNULLtoString(roleids))) {
			String hql = " and roleid in " + roleids.replace("[", "(").replace("]", ")").replaceAll(" ", "");
			action = action.substring(1);
			action = action.substring(action.indexOf("/") + 1);
			Menu mm = menuService.getUnique("where url=?", action);
			if (mm != null) {
				PermissionModel pm = permissionService.getUnique(" where editable=? and menuid=?" + hql, "true", mm.getId());
				if (pm != null) {
					edit = "true";
				}
				PermissionModel pm2 = permissionService.getUnique(" where department=? and menuid=?" + hql, "true", mm.getId());
				if (pm2 != null) {
					department = "true";
				}
			}
		}
		writeStringToClient(response, "{edit:" + edit + ",department:" + department + "}", true);
	}

	public void listPermissionsByRole() {
		List<PermissionModel> pmList = permissionService.listByParams(" where roleid=?", roleid);
		writeListToClient(response, pmList, true);
	}

	public void roleTreeList() {
		List<RoleModel> rolelist = new ArrayList<RoleModel>();
		rolelist = roleService.listByParams("where editable=?", "true");
		List<TreeModel> treelist = new ArrayList<TreeModel>();
		if (!rolelist.isEmpty()) {
			for (RoleModel role : rolelist) {
				TreeModel node = new TreeModel();
				node.setId(role.getId().toString());
				node.setSortIndex(role.getRindex());
				node.setText(role.getName());
				node.setIconCls("role");
				node.setLeaf(true);
				treelist.add(node);
			}
		}
		writeListToClient(response, treelist, true);
	}

	public void savePerms() {
		List<PermissionModel> pmList = JSON.parseArray(jsonToSave, PermissionModel.class);
		if (roleid != 0) {
			permissionService.delByParams(" where roleid=?", roleid);
		}
		for (PermissionModel perm : pmList) {
			permissionService.saveOrUpdate(perm);
		}
		writeResultToClient(response, true);
	}

	public void editRole() {
		role.setEditable("true");
		roleService.saveOrUpdate(role);
		writeResultToClient(response, true);
	}

	public void uniqueUser() {
		UserModel user = userService.getUnique(" where username=?", username);
		if (user != null && user.getId() != id) {
			writeStringToClient(response, "登录名重复！", true);
		} else {
			UserModel user2 = userService.getUnique(" where unum=?", unum);
			if (user2 != null && user2.getId() != id) {
				writeStringToClient(response, "工号/学号重复！", true);
			} else {
				writeStringToClient(response, "true", true);
			}
		}
	}

	public void editUser() {
		user.setEditable("true");
		user.setRegisterDate(new Date());
		userService.saveOrUpdate(user);

		RoleModel r = roleService.getUnique(" where name='普通用户'");
		if (r != null) {
			UserRole ur = new UserRole();
			ur.setUserid(user.getId());
			ur.setRoleid(r.getId());
			userRoleService.saveOrUpdate(ur);
		}
		writeResultToClient(response, true);
	}

	public void delRole() {
		if (delIds != null) {
			for (int i = 0; i < delIds.length; i++) {
				roleService.delete(delIds[i]);
				userRoleService.delByParams(" where roleid=?", delIds[i]);
			}
		}
		writeResultToClient(response, true);
	}

	public void removeUserFromRole() {
		if (delIds != null) {
			for (int i = 0; i < delIds.length; i++) {
				userRoleService.delByParams(" where userid=? and roleid=?", delIds[i], roleid);
			}
		}
		writeResultToClient(response, true);
	}

	public void addUserToRole() {
		List<UserRole> urList = userRoleService.listByParams(" where userid=? and roleid=?", userid, roleid);
		if (urList == null || (urList != null && urList.isEmpty())) {
			UserRole ur = new UserRole();
			ur.setUserid(userid);
			ur.setRoleid(roleid);
			userRoleService.saveOrUpdate(ur);
		}
	}

	public void delUser() {
		if (delIds != null) {
			for (int i = 0; i < delIds.length; i++) {
				userService.delete(delIds[i]);
				userRoleService.delByParams(" where userid=?", delIds[i]);
			}
		}
		writeResultToClient(response, true);
	}

	public void findRole() {
		RoleModel role = roleService.get(id);
		writeObjectToClient(response, role, true);
	}

	public void findUser() {
		UserModel user = userService.get(id);
		writeObjectToClient(response, user, true);
	}

	/*
	 * 为角色授权使用，列出未勾选任何菜单的空checked列表
	 */
	public void list() {
		List<Menu> menulist = new ArrayList<Menu>();
		if ("accordions".equals(action)) {
			menulist = menuService.listByParams(" where pid=? order by sortIndex", -1);
		} else if ("treenode".equals(action)) {
			menulist = menuService.listByParams(" where pid=? order by sortIndex", id);
		}
		writeListToClient(response, menulist, true);
	}

	/*
	 * 系统根据权限加载菜单
	 */
	public void listMenuView() {
		roleids = "(" + roleids.substring(1, roleids.length() - 1).replaceAll(" ", "") + ")";
		List<MenuView> menulist = new ArrayList<MenuView>();
		if ("accordions".equals(action)) {
			menulist = menuViewService.listByParams(" where pid=? and roleid in " + roleids + " order by sortIndex", -1);
		} else if ("treenode".equals(action)) {
			menulist = menuViewService.listByParams(" where pid=? and roleid in " + roleids + " order by sortIndex", id);
		}
		if (ListUtil.filterList(menulist)) {
			for (int i = 0; i < menulist.size() - 1; i++) {
				for (int j = menulist.size() - 1; j > i; j--) {
					if (menulist.get(j).getId() == menulist.get(i).getId()) {
						menulist.remove(j);
					}
				}
			}
		}
		writeListToClient(response, menulist, true);
	}

	/*
	 * 为流程节点选择用户
	 */
	public void queryUserListByParamsUnderRole() {
		RoleModel rm = null;
		String hql = "";
		if (roleid != null && roleid != 0) {
			rm = roleService.get(roleid);
			hql = " where roleid=? and editable='true' ";
		} else {
			if (n1 != null && n1 != 0) {
				rm = roleService.get(n1);
				if (fname != null) {
					hql = " where roleid=? and " + fname + " like '%" + fvalue + "%' and editable='true' ";
				} else {
					hql = " where roleid=? and editable='true' ";
				}
			}
		}
		if (rm != null) {
			Page<RoleUserViewModel> ruvmList = roleUserViewService.listByParams(page, limit, hql, rm.getId());
			writePageListToClient(response, ruvmList);
		}
	}

	/*
	 * 为角色添加用户
	 */
	public void queryUserListUnderRole() {
		Page<UserRole> userRolelist = userRoleService.listByParams(page, limit, " where roleid=?", id);
		Page<UserModel> userPage = new Page<UserModel>();
		userPage.setHasNext(userRolelist.isHasNext());
		userPage.setHasPre(userRolelist.isHasPre());
		userPage.setIndex(userRolelist.getIndex());
		List<UserModel> uList = new ArrayList<UserModel>();
		int pageSize = 0;
		if (userPage != null && userPage.getItems() != null) {
			pageSize = userPage.getItems().size();
		}
		PageContext<UserModel> context = new PageContext<UserModel>(userPage.getItems(), pageSize);
		userPage.setContext(context);
		if (userRolelist != null && !userRolelist.getItems().isEmpty()) {
			for (UserRole urole : userRolelist.getItems()) {
				UserModel user = userService.get(urole.getUserid());
				uList.add(user);
			}
			userPage.setItems(uList);
		}
		writePageListToClient(response, userPage);
	}

	// 用户管理，查询功能url[0]
	public void queryUserListByParams() {
		Page<UserModel> userlist = userService.listByParams(page, limit, " where editable=? and " + fname + " like ? order by registerDate,id", "true", "%" + fvalue + "%");
		writePageListToClient(response, userlist);
	}

	/*
	 * 用户管理url[1]
	 */
	public void userList() {
		Page<UserModel> userlist = null;
		if (overdepartment != null && "true".equals(overdepartment)) {
			userlist = userService.listByParams(page, limit, " where editable<>? order by registerDate,id", "false");
		} else {
			if (!"".equals(StringUtil.parseNULLtoString(deptname))) {
				userlist = userService.listByParams(page, limit, " where editable<>? and department=? order by registerDate,id", "false", deptname);
			} else {
				userlist = userService.listByParams(page, limit, " where editable<>? order by registerDate,id", "false");
			}
		}
		writePageListToClient(response, userlist);
	}

	public void roleList() {
		Page<RoleModel> rolelist = roleService.listByParams(page, limit, " where editable<>? order by rindex", "false");
		writePageListToClient(response, rolelist);
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public UserModel getUser() {
		return user;
	}

	public void setUser(UserModel user) {
		this.user = user;
	}

	public RoleModel getRole() {
		return role;
	}

	public void setRole(RoleModel role) {
		this.role = role;
	}

	public Integer getRoleid() {
		return roleid;
	}

	public void setRoleid(Integer roleid) {
		this.roleid = roleid;
	}

	public int getUserid() {
		return userid;
	}

	public void setUserid(int userid) {
		this.userid = userid;
	}

	public String getJsonToSave() {
		return jsonToSave;
	}

	public void setJsonToSave(String jsonToSave) {
		this.jsonToSave = jsonToSave;
	}

	public String getRoleids() {
		return roleids;
	}

	public void setRoleids(String roleids) {
		this.roleids = roleids;
	}

	public String getRolename() {
		return rolename;
	}

	public void setRolename(String rolename) {
		this.rolename = rolename;
	}

	public Integer[] getRoleidArray() {
		return roleidArray;
	}

	public void setRoleidArray(Integer[] roleidArray) {
		this.roleidArray = roleidArray;
	}

	public int getMenuid() {
		return menuid;
	}

	public void setMenuid(int menuid) {
		this.menuid = menuid;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getUnum() {
		return unum;
	}

	public void setUnum(String unum) {
		this.unum = unum;
	}

	public String getDeptname() {
		return deptname;
	}

	public void setDeptname(String deptname) {
		this.deptname = deptname;
	}
}
